package com.japp.sys.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.japp.base.BaseAction;
import com.japp.sys.bean.UploadFile;
import com.japp.sys.service.UploadService;

/**
 * 上传下载杀出
 * @author jion
 */
@Scope("prototype")
@Controller
public class UploadFileAction extends BaseAction<UploadFile> {

    private static final long serialVersionUID = 1L;
    @Autowired
    private UploadService uploadFileService;
    private UploadFile        uploadFile;
    private String[]          uploadifyFileName;
    private String[]          uploadifyContentType;
    private File[]            uploadify;
    private String            conId;
    private String            fileFolder;
    private List<UploadFile>  uploadFileList;
    private String            ajaxResult;
    private String            fileId;

    /**
     * 附件查询
     * @return
     * @throws Exception
     */
    public String findUploadById() throws Exception {
        this.uploadFile = new UploadFile();
        if (conId!=null && !"".equals(this.conId)&& this.fileFolder!=null&& !"".equals(this.fileFolder)) {
            this.uploadFile.setConId(new Integer(this.conId));
            this.uploadFile.setFileFolder(this.fileFolder);
        }
        this.uploadFileList = this.uploadFileService.queryListUploadByUpload(uploadFile);
        return "fileLsit";
    }

    /**
     * 根据id删除
     * 
     * @return
     */
    public String deleteById() {
        int rslt = 0;
        try {
            if (fileId!=null && !"".equals(fileId)) {
                // tomcat的项目 路径
                String realPath = ServletActionContext.getServletContext().getRealPath("\\");
                UploadFile uf = uploadFileService.queryUploadById(Integer.valueOf(fileId));
                if (null != uf) {
                    String filePath = realPath + uf.getRealPath();
                    File file = new File(filePath);
                    file.delete();
                }
                rslt = this.uploadFileService.deleteUploadById(new Integer(fileId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (rslt!=0) {
            this.ajaxResult = "success";
        } else {
            this.ajaxResult = "error";
        }
        request.setAttribute("result", rslt);
        return "delete_result";
    }

    /**
     * 根据一组id删除附件
     */
    public int deleteByArray(String[] keys,String fileFolder) {
        int rel = 0;
        try {
        	if(keys!=null&&keys.length>0&&fileFolder!=null&&!"".equals(fileFolder.trim())){

                // tomcat的项目 路径
                String realPath = ServletActionContext.getServletContext().getRealPath("\\");
                String str = uploadFileService.queryUploadSplitByUpload(keys,fileFolder);
                if(str!=null&&str.length()!=0){
                	String filePath = "";
                	String[] keyUrl = str.split(",");
                	File file = null;
                	for(String s:keyUrl){
                		filePath = realPath + s;
                        file = new File(filePath);
                		if(file.delete()){
                			System.out.println("删除成功:"+filePath);
                		}
                    }
                	rel = this.uploadFileService.deleteUploadByIds(keys,fileFolder);
                }
        	}
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return rel;
    }
    
    
    
    /**
     * 根据一组id删除附件
     */
    public String deleteByIdList() {
        Integer rslt = 0;
        List<Integer> conIdList = new ArrayList<Integer>();
        try {
            String tempIds[] = conId.split(",");

            for (String tempConId : tempIds) {
                conIdList.add(new Integer(tempConId));
            }
            if (null != fileFolder && !"".equals(fileFolder)) {
                rslt = this.uploadFileService.deleteUploadByIds((String[])conIdList.toArray(),fileFolder);
            } else {
                this.ajaxResult = "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.ajaxResult = "error";
        }
        if (rslt == 0) {
            this.ajaxResult = "success";
        } else {
            this.ajaxResult = "error";
        }
        request.setAttribute("result", rslt);
        //this.getRequest().put("result", rslt);
        return null;
    }

    /**
     * 上传附件
     * 
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String addFiles() {
        FileOutputStream outStream = null;
        FileInputStream inStream = null;
        PrintWriter out = null;
        Object uid = null;
        if(session!=null&&session.getAttribute("u_id")!=null){
        	uid = session.getAttribute("u_id");
        }else{
        	return "";
        }
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            out = response.getWriter();
            String conId = (String) request.getParameter("conId");
            String fileFolder = (String) request.getParameter("fileFolder");
            if (conId==null || fileFolder==null
                    || "".equals(fileFolder)) {
                out.write("error");
                return null;
            }

            this.uploadFile = new UploadFile();
            if (conId!=null && !"".equals(conId)
                    && fileFolder!=null
                    && !"".equals(fileFolder)) {
                this.uploadFile.setConId(new Integer(conId));
                this.uploadFile.setFileFolder(fileFolder);
            }
            this.uploadFileList = this.uploadFileService.queryListUploadAll(uploadFile);
            if (null != uploadFileList
                    && (uploadFileList.size() + uploadify.length) > 5) {
                return null;
            }

            String itemName = fileFolder.split("_") != null ? fileFolder
                    .split("_")[0] : "";
            String tableName = fileFolder.split("_") != null ? fileFolder
                    .split("_")[1] : "";
            // 新文件名要加入日期
            Date date = null;
            // tomcat的项目 路径
            String realPath = ServletActionContext.getServletContext()
                    .getRealPath("\\");
            // 项目中存放路径
            String oppositePath = "upload\\";
            // 判断 存放的文件夹是否存在
            File dir = new File(realPath + oppositePath + itemName);
            if (!dir.isDirectory()) {
                dir.mkdir();// 新建
            }
            File dir1 = new File(realPath + oppositePath + itemName + "\\"
                    + tableName);
            if (!dir1.isDirectory()) {
                dir1.mkdir();// 新建
            }
            oppositePath = oppositePath + itemName + "\\" + tableName + "\\";
            // 新文件名容器
            StringBuilder strBuilder = new StringBuilder("");
            // 输出文件
            File outFile = null;
            // 获取多文件个数
            int length = uploadify != null && uploadify.length > 0 ? uploadify.length
                    : 0;

            // 循环保存
            for (int i = 0; i < length; i++) {
                // 根据日期构造新文件名，防止命名冲突
                date = new Date();
                DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String today = df.format(date);
                // 拼接新文件名字符串
                strBuilder.append(uploadifyFileName[i]);
                int k = strBuilder.lastIndexOf(".");
                strBuilder.insert(k, today);
                oppositePath = oppositePath + strBuilder.toString();
                System.out.println("上传文件名：" + uploadifyFileName[i]);
                System.out.println("项目中存放路径：" + oppositePath);
                System.out.println("上传路径：" + realPath + oppositePath);
                System.out.println("上传时间："
                        + new SimpleDateFormat("yyyy-MM-dd HH:mm")
                                .format(new Date()));
                outFile = new File(realPath + oppositePath);
                outStream = new FileOutputStream(outFile);
                inStream = new FileInputStream(uploadify[i]);
                byte[] buffer = new byte[1024];
                int l = 0;
                while ((l = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, l);
                }
                // 插入到附件表
                UploadFile uploadFileItem = new UploadFile();
                uploadFileItem.setFileName(uploadifyFileName[i]);
                uploadFileItem.setFileUrl(realPath + oppositePath);
                uploadFileItem.setUploadTime(new Date());
                uploadFileItem.setUploadUser((int) uid);
                uploadFileItem.setConId(new Integer(conId));
                uploadFileItem.setFileFolder(fileFolder);
                uploadFileItem.setRealPath(oppositePath);
                Integer rslt = (Integer) this.uploadFileService.insertUpload(uploadFileItem);
                out.print(strBuilder.toString() + "," + conId + ","+ fileFolder +",成功条数:"+rslt);
            }
            
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
        	try {
        		if(inStream!=null)inStream.close();
	        	if(outStream!=null)outStream.close();
	        	if(out!=null){
	        		out.flush();
		            out.close();
	        	}
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return null;
    }

    /**
     * 下载附件
     * 
     * @return
     */
    public String downloadFile() {
        OutputStream out = null;
        FileInputStream in = null;
        String fileDownload = ""; // 下载的文件的物理路径＋文件名
        String fileDisplay = ""; // 下载文件名
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            UploadFile activeItem = new UploadFile();
            if (fileId!=null && !"".equals(fileId)) {
                activeItem = this.uploadFileService.queryUploadById(Integer.valueOf(fileId));
            } else {
                activeItem = new UploadFile();
                activeItem.setFileName("");
                activeItem.setFileUrl("");
            }
            fileDownload = activeItem.getFileUrl();
            fileDisplay = activeItem.getFileName();

            fileDisplay = URLEncoder.encode(fileDisplay, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + fileDisplay);
            out = response.getOutputStream();
            in = new FileInputStream(fileDownload);
            byte[] b = new byte[4096];
            int i = 0;
            while ((i = in.read(b)) > 0) {
                out.write(b, 0, i);
            }
            out.flush();
            if (out != null) {
                out.close();
                out = null;
            }
            if (in != null) {
                in.close();
                in = null;
            }
            this.ajaxResult = "success";
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            this.ajaxResult = "error";
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            this.ajaxResult = "error";
            e.printStackTrace();
        } catch (Exception e) {
            // TODO: handle exception
            this.ajaxResult = "error";
            e.printStackTrace();
        }finally{
        	try {
				if(in!=null)in.close();
	        	if(out!=null)out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return null;
    }

    public String[] getUploadifyFileName() {
        return uploadifyFileName;
    }

    public void setUploadifyFileName(String[] uploadifyFileName) {
        this.uploadifyFileName = uploadifyFileName;
    }

    public String[] getUploadifyContentType() {
        return uploadifyContentType;
    }

    public void setUploadifyContentType(String[] uploadifyContentType) {
        this.uploadifyContentType = uploadifyContentType;
    }

    public File[] getUploadify() {
        return uploadify;
    }

    public void setUploadify(File[] uploadify) {
        this.uploadify = uploadify;
    }

    public UploadFile getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(UploadFile uploadFile) {
        this.uploadFile = uploadFile;
    }

    public String getConId() {
        return conId;
    }

    public void setConId(String conId) {
        this.conId = conId;
    }

    public String getFileFolder() {
        return fileFolder;
    }

    public void setFileFolder(String fileFolder) {
        this.fileFolder = fileFolder;
    }

    public List<UploadFile> getUploadFileList() {
        return uploadFileList;
    }

    public void setUploadFileList(List<UploadFile> uploadFileList) {
        this.uploadFileList = uploadFileList;
    }

    public String getAjaxResult() {
        return ajaxResult;
    }

    public void setAjaxResult(String ajaxResult) {
        this.ajaxResult = ajaxResult;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }
}
